#include "conversationmodel.h"
#include <QtDebug>
#include <QColor>

#define MAX_RECEIVE_SIZE 128

QHash<int, QByteArray> ConversationModel::sRoleNames = {
    {Role::Content, "content"},
    {Role::MyMsg, "myMsg"},
    {Role::Color, "bg_color"}
};

ConversationModel::ConversationModel(QObject *parent) : QAbstractListModel(parent)
{
}

ConversationModel::~ConversationModel() = default;

void ConversationModel::add(const QString& content, int color, bool myMsg) {
    int index = mConversationList.size();
    beginInsertRows(QModelIndex(), index, index);
    mConversationList.push_back(Item(content, color, myMsg));
    endInsertRows();
}

void ConversationModel::clear(int count) {
    if (count <= 0) {
        beginRemoveRows(QModelIndex(), 0, mConversationList.size() - 1);
        mConversationList.clear();
        endRemoveRows();
    } else {
        count = qMin(count, mConversationList.size());
        beginRemoveRows(QModelIndex(), 0, count - 1);
        while (count) {
            mConversationList.removeFirst();
            count --;
        }
        endRemoveRows();
    }
}

// QAbstractItemModel interface
int ConversationModel::rowCount(const QModelIndex &parent) const {
    (void) parent;
    return mConversationList.size();
}

QVariant ConversationModel::data(const QModelIndex &index, int role) const {
    switch (role) {
    case Role::Content:
        return QVariant::fromValue(mConversationList[index.row()].content);
    case Role::Color:
        return QVariant::fromValue(mConversationList[index.row()].color);
    case Role::MyMsg:
        return QVariant::fromValue(mConversationList[index.row()].myMsg);
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> ConversationModel::roleNames() const {
    return sRoleNames;
}

/////////////////////////
// Item
ConversationModel::Item::Item(const QString& content, int color, bool myMsg) :
    content(content),
    color(color),
    myMsg(myMsg)
{
}

ConversationModel::Item::~Item() = default;
